package com.sbio.udiapp.util;

import android.content.Context;
import android.content.SharedPreferences;

import java.util.Map;

public class SharedPreferencesUtil {
    private static final String PREFERENCE_FILE_NAME = "MySharedPreferences";
    private static SharedPreferences sharedPreferences;
    private static SharedPreferences.Editor editor;

    private SharedPreferencesUtil() {
        // 私有构造函数，确保该类不会被实例化
    }

    public static void init(Context context) {
        if (sharedPreferences == null) {
            sharedPreferences = context.getSharedPreferences(PREFERENCE_FILE_NAME, Context.MODE_PRIVATE);
            editor = sharedPreferences.edit();
        }
    }

    public static void saveString(String key, String value) {
        checkInitialization();
        editor.putString(key, value).apply();
    }

    public static String getString(String key) {
        checkInitialization();
        return sharedPreferences.getString(key, "");
    }

    public static Map<String,?> getAll() {
        checkInitialization();
        return sharedPreferences.getAll();
    }

    public static String getString(String key, String defaultValue) {
        checkInitialization();
        return sharedPreferences.getString(key, defaultValue);
    }

    public static void saveBoolean(String key, boolean value) {
        checkInitialization();
        editor.putBoolean(key, value).apply();
    }

    public static boolean getBoolean(String key) {
        checkInitialization();
        return sharedPreferences.getBoolean(key, false);
    }

    public static boolean getBoolean(String key, boolean defaultValue) {
        checkInitialization();
        return sharedPreferences.getBoolean(key, defaultValue);
    }

    public static void removeKey(String key) {
        checkInitialization();
        editor.remove(key).apply();
    }

    public static void clearAll() {
        checkInitialization();
        editor.clear().apply();
    }

    private static void checkInitialization() {
        if (sharedPreferences == null || editor == null) {
            throw new IllegalStateException("SharedPreferencesUtil is not initialized. Call init() first.");
        }
    }
}
